﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Collections.ObjectModel;

namespace Coding4Fun.PrinterDisplayHack
{
    /// <summary>
    /// Interaction logic for FindPrinters.xaml
    /// </summary>
    public partial class FindPrinters : Window
    {
        public string SelectedIpAddress { get; set; }

        public ObservableCollection<LocalPrinter> Printers
        {
            get { return (ObservableCollection<LocalPrinter>)GetValue(PrintersProperty); }
            set { SetValue(PrintersProperty, value); }
        }
        public static readonly DependencyProperty PrintersProperty = DependencyProperty.Register("Printers", typeof(ObservableCollection<LocalPrinter>), typeof(FindPrinters), new UIPropertyMetadata(null));


        public FindPrinters()
        {
            InitializeComponent();

            LocatePrinters();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            LocatePrinters();
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                LocalPrinter lstSelected = (LocalPrinter)e.AddedItems[0];

                if (lstSelected != null)
                {
                    SelectedIpAddress = lstSelected.Address.ToString();
                    this.btnSelect.IsEnabled = true;
                }
            }
        }

		private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (e.Source != null)
				CloseWithSelection();
		}

        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            CloseWithSelection();
        }

		private void LocatePrinters()
		{
			this.btnSelect.IsEnabled = false;
			SelectedIpAddress = "";

			Printers = new ObservableCollection<LocalPrinter>();

			List<LocalPrinter> tmpList = PrinterUtils.GetPrinters();

			foreach (LocalPrinter printer in tmpList)
				this.Printers.Add(printer);
		}

        private void CloseWithSelection()
        {
            if (!String.IsNullOrWhiteSpace(SelectedIpAddress))
            {
                this.DialogResult = true;
                this.Close();
            }
        }
    }
}
